<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 教师申请入驻管理
 *
 * @icon fa fa-circle-o
 */
class TeacherAudit extends Backend
{

    /**
     * TeacherAudit模型对象
     * @var \app\common\model\TeacherAudit
     */
    protected $model = null;

    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\TeacherAudit;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $teacher_id = input('teacher_id/d',0);
        $where1 = [
            'teacher_audit.status' => ['neq',0],
            'teacher_audit.auto_pass' => 0
        ];
        if($teacher_id){
            $where1['user_id'] = $teacher_id;
        }

        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where1)
            ->where($where)
            ->with('user')
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 审核
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['give_lessons_str'] = $this->model->give_lessons_str($row['give_lessons']);
            $row['give_time_str'] = $this->model->give_time_str($row['give_time']);

            $before = $this->model->where([
                'id' => ['lt',$ids],
                'user_id' => $row['user_id'],
            ])->order('id desc')->find();
            $this->view->assign('before',$before);
            $this->view->assign('row', $row);

            $may_recommend = Db::name('teacher')->where('user_id',$row['user_id'])->value('recommend');
            $this->view->assign('may_recommend',!$may_recommend);
            $row['recommend'] = 0;
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if(!isset($params['status'])){
            $this->error('请选择审核状态');
        }
        $result = false;
        Db::startTrans();
        try {

            $update = [
                'status' => $params['status']
            ];
            if($params['status'] == 3){
                $update['refund_reson'] = $params['refund_reson'];
            }
            if(isset($params['recommend']) && $params['recommend']){
                $row['recommend'] = 1;
            }
            if($params['status']==2){
                \think\Hook::listen('teacher_to_pass',$row);
            }
            $result = $row->allowField(true)->save($update);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
